package org.huangrui.javase.io;

import org.junit.Test;

import java.io.*;
import java.nio.charset.Charset;

/**
 * @Author hr
 * @Create 2025-11-07 23:49
 **/
public class T01ByteToChar {
    @Test
    public void test1() throws Exception {
        try (
                // 创建字节输入流
                FileReader fr = new FileReader("GBK.txt");
        ) {
            // 读取字符
            int data;
            while ((data = fr.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test2() {
        try (
                // 创建字节输入流
                FileInputStream fis = new FileInputStream("GBK.txt");
                // 使用 InputStreamReader 将字节输入流转换为字符输入流，同时指定字符编码，例如 GBK
                InputStreamReader reader = new InputStreamReader(fis, "GBK");
        ) {
            // 读取字符
            int data;
            while ((data = reader.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test3() {
        try (
                FileWriter fw = new FileWriter("GBK.txt");
        ) {
            String data = "尚硅谷";// 写入字符
            fw.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test4() {
        try (
                // 创建字节输出流
                FileOutputStream fos = new FileOutputStream("GBK.txt");
                // 使用 OutputStreamWriter 将字符输出流转换为字节输出流，同时指定字符编码，例如 GBK
                OutputStreamWriter writer = new OutputStreamWriter(fos, "GBK");
        ) {
            String data = "尚硅谷";// 写入字符
            writer.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test5(){
        try (
                //从UTF8的文件中读取内容
                FileReader fr = new FileReader("D:\\UTF8.txt", Charset.forName("UTF-8"));
                //写内容到GBK的文件中
                FileWriter fw = new FileWriter("D:\\GBK.txt",Charset.forName("GBK"));
        ){
            int len;
            char[] data = new char[10];
            while((len = fr.read(data)) != -1){
                fw.write(data,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
